package com.realbrand.net.realbrandpay.ui.activity.wallet.set;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IProvingAccount;
import com.realbrand.net.realbrandpay.inter.IRegist;
import com.realbrand.net.realbrandpay.ui.activity.login.ForgetPasswordActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/8/7.
 */

public class VerifyMobileActivity extends BaseActivity {
    @BindView(R.id.verifyMobile_toolbar)
    Toolbar verifyMobileToolbar;
    @BindView(R.id.et_verifyactivity_mobile)
    EditText etVerifyactivityMobile;
    @BindView(R.id.iv_verifyactivity_clear)
    ImageView ivVerifyactivityClear;
    @BindView(R.id.et_verifyactivity_mobileCode)
    EditText etVerifyactivityMobileCode;
    @BindView(R.id.bt_verifyactivity_sure)
    Button btVerifyactivitySure;
    @BindView(R.id.bt_verifyactivity_sendCode)
    Button btVerifyactivitySendCode;

    //用户输入的手机号码
    private String mobile;
    //用户输入的验证码跟系统返回的验证码
    private String codeByUser;

    //定时器
    private TimeCount time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        verifyMobileToolbar.setTitle("");
        verifyMobileToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(verifyMobileToolbar);
        verifyMobileToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(VerifyMobileActivity.this, LoginActivity.class));
                finish();
            }
        });
        if (!btVerifyactivitySendCode.isClickable()) {
            btVerifyactivitySendCode.setClickable(true);
        }
        setOnClick();
        time = new TimeCount(120000, 1000);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.verifymobile_activity;
    }

    @Override
    protected void setOnClick() {
        btVerifyactivitySendCode.setOnClickListener(this);
        btVerifyactivitySure.setOnClickListener(this);
        ivVerifyactivityClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_verifyactivity_clear:
                etVerifyactivityMobile.setText("");
                mobile = null;
                break;
            case R.id.bt_verifyactivity_sendCode:
                //先获取用户输入的手机号码，然后在请求发送验证码
                btVerifyactivitySendCode.setClickable(false);
                mobile = etVerifyactivityMobile.getText().toString();
                if (TextUtils.isEmpty(mobile)) {
                    Static.toast(this, "请输入手机号码");
                } else {
                    sendCode();
                }
                break;
            case R.id.bt_verifyactivity_sure:
                //先判断用户是否输入了手机号跟验证码
                mobile = etVerifyactivityMobile.getText().toString();
                codeByUser = etVerifyactivityMobileCode.getText().toString();
                if (TextUtils.isEmpty(mobile)) {
                    Static.toast(this, "请输入手机号码");
                } else if (TextUtils.isEmpty(codeByUser)) {
                    Static.toast(this, "请输入验证码");
                } else {
                    request();
                }
                break;
        }
    }

    private void request() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("METHOD", "AccountProving");
            jsonObject.put("SOURCE", "VerifyMobileActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("UserMobile", mobile);
            jsonObject.put("Verification", codeByUser);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IRegist iForgetPassword = retrofit.create(IRegist.class);
            Call<ResponseBody> call = iForgetPassword.regist(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    //获取请求结果
                    if (response == null) {
                        Static.toast(VerifyMobileActivity.this, "网络繁忙");
                    } else {
                        try {
                            String result = response.body().string();
                            JSONObject object = new JSONObject(result);
                            JSONArray array = object.getJSONArray("DATA");
                            String s = array.getJSONObject(0).getString("result");
                            if ("true".equals(s)) {
                                //表示验证码正确，跳转到ForgetPasswordActivity
                                Intent intent = new Intent(VerifyMobileActivity.this, ForgetPasswordActivity.class);
                                intent.putExtra("mobile", mobile);
                                startActivity(intent);
                                finish();
                            } else if ("验证码错误".equals(s)) {
                                Static.toast(VerifyMobileActivity.this, "验证码错误");
                            } else if ("验证码已过时".equals(s)) {
                                Static.toast(VerifyMobileActivity.this, "验证码已超时");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void sendCode() {
        JSONObject object = new JSONObject();
        try {
            object.put("METHOD", "AccountProving");
            object.put("SOURCE", "VerifyMobileActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("UserMobile", mobile);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IProvingAccount iGetCode = retrofit.create(IProvingAccount.class);
            Call<ResponseBody> code = iGetCode.getCode(body);
            code.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(VerifyMobileActivity.this, "网络繁忙");
                    } else {
                        //获取返回结果
                        try {
                            String result = response.body().string();
                            L.d(L.TAG, "忘记密码请求验证码result：" + result);
                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray array = jsonObject.getJSONArray("DATA");
                            String resultVerify = array.getJSONObject(0).getString("result");
                            if ("false".equals(resultVerify)) {
                                Static.toast(VerifyMobileActivity.this, "该手机号码未注册");
                            } else if ("true".equals(resultVerify)) {
                                time.start();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    btVerifyactivitySendCode.setClickable(true);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btVerifyactivitySendCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            btVerifyactivitySendCode.setClickable(false);
            btVerifyactivitySendCode.setText(millisUntilFinished / 1000 + "s" + "后可重发");
        }

        @Override
        public void onFinish() {
            btVerifyactivitySendCode.setText("重新获取验证码");
            btVerifyactivitySendCode.setClickable(true);
            btVerifyactivitySendCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
        }
    }
}
